﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ServiceModel;

namespace DMSClient
{
    public partial class frmImportClassification : Form
    {
        WSHttpBinding httpBinding = new WSHttpBinding();
        EndpointAddress address = new EndpointAddress(Properties.Settings.Default.Server);
        DataTable dtP;
        DataTable dtH;
        string ambiente;
        DataSet ds;
        DataTable dt2;

        public frmImportClassification()
        {
            InitializeComponent();
            ambiente = Properties.Settings.Default.CurrentEnv;
            httpBinding.MaxReceivedMessageSize = 2147483647;
            httpBinding.MaxBufferPoolSize = 2147483647;
            httpBinding.CloseTimeout = TimeSpan.MaxValue;
            httpBinding.ReceiveTimeout = TimeSpan.MaxValue;
            httpBinding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;
            httpBinding.Security.Mode = SecurityMode.None;

            DMSServices.DMSServicesClient cliente = new DMSServices.DMSServicesClient(httpBinding, address);
            this.Text = Properties.Settings.Default.CurrentEnvDes + " - Store Classification";
            uceCountry.DisplayMember = "dsCountry";
            uceCountry.ValueMember = "cdCountry";
            uceCountryIV.DisplayMember = "dsCountry";
            uceCountryIV.ValueMember = "cdCountry";
            uceCountryHIV.DisplayMember = "dsCountry";
            uceCountryHIV.ValueMember = "cdCountry";

            string distributors = null;

            try
            {
                cliente.Open();
                distributors = cliente.getCountryList(ambiente);
                cliente.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(Properties.Settings.Default.DistributorsListErrorMsg, ex.InnerException);
            }
            if (distributors == null)
            {
                throw new Exception(Properties.Settings.Default.DistributorsNullListErrorMsg);
            }


            DataTable dt = new DataTable("dtCountryList");
            dt.Columns.Add("idCountry");
            dt.Columns.Add("cdCountry");
            dt.Columns.Add("dsCountry");

            DataSet ds = new DataSet("dsCountryList");
            ds.Tables.Add(dt);

            System.IO.StringReader xmlSR = new System.IO.StringReader(distributors);
            ds.ReadXml(xmlSR, XmlReadMode.ReadSchema);
            uceCountry.DataSource = dt;
            uceCountryIV.DataSource = dt;
            uceCountryHIV.DataSource = dt;
            uceCountry.SelectedIndex = 0;
            uceCountryIV.SelectedIndex = 0;
            uceCountryHIV.SelectedIndex = 0;
            xmlSR.Close();
        }

        private void ubSearch_Click(object sender, EventArgs e)
        {
            cambio(false);
            bgwClass.RunWorkerAsync();
            
        }

        public DataTable filtroTabla(DataTable tab, string filtro)
        {
            try
            {
                DataRow[] rows;
                DataTable dtNew = tab.Clone();

                rows = tab.Select(filtro);

                foreach (DataRow row in rows)
                {
                    dtNew.ImportRow(row);
                }
                return dtNew;
            }
            catch (Exception e) {
                MessageBox.Show(e.Message);
                return null;
            }
        }

        private void cambio(bool estado)
        {
            ubExport.Enabled = estado;
            ubSearch.Enabled = estado;
            ugClass.Enabled = estado;
            uceCountry.Enabled = estado;

            loader1.Visible = !estado;

            ubExportIV.Enabled = estado;
            ubSearchIV.Enabled = estado;
            ugClassIV.Enabled = estado;
            uceCountryIV.Enabled = estado;

            loader2.Visible = !estado;

            ubExportHIV.Enabled = estado;
            ubSearchHIV.Enabled = estado;
            ugClassHIV.Enabled = estado;
            uceCountryHIV.Enabled = estado;

            loader3.Visible = !estado;
        }

        private void bgwClass_DoWork(object sender, DoWorkEventArgs e)
        {
            DMSServices.DMSServicesClient cliente = new DMSServices.DMSServicesClient(httpBinding, address);
            string listarClass = null;
            BackgroundWorker worker = sender as BackgroundWorker;
            try {
                cliente.Open();
                listarClass = cliente.getClassificationReport(uceCountry.Value.ToString(), ambiente);
                cliente.Close();
                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(Properties.Settings.Default.ReportErrorMsg, ex.InnerException);
            }
            if (listarClass == null) throw new Exception(Properties.Settings.Default.ReportNullErrorMsg);
            
            dt2 = new DataTable("Classificationdt");
            dt2.Columns.Add("idParentClassification");
            dt2.Columns.Add("idClassification");
            dt2.Columns.Add("cdClassification");
            dt2.Columns.Add("nmClassification");
            DataSet ds = new DataSet("Classification");
            ds.Tables.Add(dt2);

            System.IO.StringReader xmlSR = new System.IO.StringReader(listarClass);
            ds.ReadXml(xmlSR, XmlReadMode.ReadSchema);
            xmlSR.Close();
        }

        private void bgwClass_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                if (!this.IsDisposed)
                {
                    this.BringToFront();
                    MessageBox.Show(this, e.Error.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    cambio(true);
                }
            }
            else if (!e.Cancelled && !this.IsDisposed)
            {
                dtP = filtroTabla(dt2, "idParentClassification = 0");
                dtP.Columns.Remove("idParentClassification");
                dtP.TableName = "padre";
                dtH = filtroTabla(dt2, "idParentClassification <> 0");
                dtH.Columns.Remove("idClassification");
                dtH.TableName = "hijo";

                if (dtH.Rows.Count > 0)
                {
                    DataSet dsMaestro = new DataSet();
                    dsMaestro.Tables.Add(dtP);
                    dsMaestro.Tables.Add(dtH);
                    DataColumn dcPadre = new DataColumn();
                    DataColumn dcHijo = new DataColumn();

                    dcPadre = dsMaestro.Tables["padre"].Columns["idClassification"];
                    dcHijo = dsMaestro.Tables["hijo"].Columns["idParentClassification"];

                    DataRelation drRel = new DataRelation("Relacion", dcPadre, dcHijo);
                    dsMaestro.Relations.Add(drRel);
                    ugClass.DataSource = dsMaestro;
                }
                else
                {
                    ugClass.DataSource = dtP;
                }

                try
                {
                    ugClass.DisplayLayout.Bands[0].Columns["idClassification"].Hidden = true;
                    ugClass.DisplayLayout.Bands[1].Columns["idParentClassification"].Hidden = true;
                }
                catch (Exception exc)
                {
                    //MessageBox.Show(exc.Message);
                }
                cambio(true);
            }
        }

        private void ultraTabControl1_SelectedTabChanged(object sender, Infragistics.Win.UltraWinTabControl.SelectedTabChangedEventArgs e)
        {

        }

        private void ubExport_Click(object sender, EventArgs e)
        {
            if (ugClass.Rows.Count < 1)
            {
                MessageBox.Show(this, "There is no data to export", "Store Classification Report", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            System.Windows.Forms.SaveFileDialog dialogo = new System.Windows.Forms.SaveFileDialog();
            dialogo.DefaultExt = "xls";
            Infragistics.Win.UltraWinGrid.ExcelExport.UltraGridExcelExporter Exporter = new Infragistics.Win.UltraWinGrid.ExcelExport.UltraGridExcelExporter();
            if (dialogo.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                Exporter.Export(ugClass, dialogo.FileName);
                if (MessageBox.Show(this, "Do you want to open the file?", "Store Classification Report", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    System.Diagnostics.Process.Start(dialogo.FileName);
                }
            }
        }

        private void centrarLoader()
        {
            loader1.Left = (this.Width - loader1.Width) / 2;
            loader1.Top = ((this.Height - loader1.Height) / 2) - loader1.Height;

            loader2.Left = (this.Width - loader2.Width) / 2;
            loader2.Top = ((this.Height - loader2.Height) / 2) - loader2.Height;

            loader3.Left = (this.Width - loader3.Width) / 2;
            loader3.Top = ((this.Height - loader3.Height) / 2) - loader3.Height;
        }

        private void frmClassification_Shown(object sender, EventArgs e)
        {
            centrarLoader();
        }

        private void frmClassification_Resize(object sender, EventArgs e)
        {
            centrarLoader();
        }

        private void ubwClassIV_DoWork(object sender, DoWorkEventArgs e)
        {
            DMSServices.DMSServicesClient cliente = new DMSServices.DMSServicesClient(httpBinding, address);
            string listarImportClass = null;
            BackgroundWorker worker = sender as BackgroundWorker;
            try
            {
                cliente.Open();
                listarImportClass = cliente.getImportClass(uceCountryIV.Value.ToString(), ambiente);
                cliente.Close();
                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(Properties.Settings.Default.ReportErrorMsg, ex.InnerException);
            }
            if (listarImportClass == null) throw new Exception(Properties.Settings.Default.ReportNullErrorMsg);

            DataTable dt = new DataTable("ImportClassdt");
            dt.Columns.Add("cdClassification");
            dt.Columns.Add("cdClassificationType");
            dt.Columns.Add("nmClassification");
            dt.Columns.Add("nrLevel");
            ds = new DataSet("ImportClassds");
            ds.Tables.Add(dt);

            System.IO.StringReader xmlSR = new System.IO.StringReader(listarImportClass);
            ds.ReadXml(xmlSR, XmlReadMode.ReadSchema);
            xmlSR.Close();
        }

        private void ubwClassIV_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                if (!this.IsDisposed)
                {
                    this.BringToFront();
                    MessageBox.Show(this, e.Error.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    cambio(true);
                }
            }
            else if (!e.Cancelled && !this.IsDisposed)
            {
                ugClassIV.DataSource = ds;
                cambio(true);
            }
        }

        private void ubSearchIV_Click(object sender, EventArgs e)
        {
            cambio(false);
            bgwClassIV.RunWorkerAsync();
        }

        private void ubExportIV_Click(object sender, EventArgs e)
        {
            if (ugClassIV.Rows.Count < 1)
            {
                MessageBox.Show(this, "There is no data to export", "Store Classification Report", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            System.Windows.Forms.SaveFileDialog dialogo = new System.Windows.Forms.SaveFileDialog();
            dialogo.DefaultExt = "xls";
            Infragistics.Win.UltraWinGrid.ExcelExport.UltraGridExcelExporter Exporter = new Infragistics.Win.UltraWinGrid.ExcelExport.UltraGridExcelExporter();
            if (dialogo.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                Exporter.Export(ugClassIV, dialogo.FileName);
                if (MessageBox.Show(this, "Do you want to open the file?", "Store Classification Report", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    System.Diagnostics.Process.Start(dialogo.FileName);
                }
            }
        }

        private void uceCountry_ValueChanged(object sender, EventArgs e)
        {
            try
            {
                ugClass.DataSource = null;
            }
            catch { }
        }

        private void uceCountryIV_ValueChanged(object sender, EventArgs e)
        {
            try
            {
                ugClassIV.DataSource = null;
            }
            catch { }
        }

        private void bgwClassHIV_DoWork(object sender, DoWorkEventArgs e)
        {
            DMSServices.DMSServicesClient cliente = new DMSServices.DMSServicesClient(httpBinding, address);
            string listarImportClassH = null;
            BackgroundWorker worker = sender as BackgroundWorker;
            try
            {
                cliente.Open();
                listarImportClassH = cliente.getImportClassH(uceCountryHIV.Value.ToString(), ambiente);
                cliente.Close();
                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(Properties.Settings.Default.ReportErrorMsg, ex.InnerException);
            }
            if (listarImportClassH == null) throw new Exception(Properties.Settings.Default.ReportNullErrorMsg);

            DataTable dt = new DataTable("ClassificationHierarchydt");
            dt.Columns.Add("cdParentClassification");
            dt.Columns.Add("cdChildClassification");
            dt.Columns.Add("cdClassificationType");

            ds = new DataSet("ClassificationHierarchyds");
            ds.Tables.Add(dt);

            System.IO.StringReader xmlSR = new System.IO.StringReader(listarImportClassH);
            ds.ReadXml(xmlSR, XmlReadMode.ReadSchema);
            xmlSR.Close();
        }

        private void bgwClassHIV_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                if (!this.IsDisposed)
                {
                    this.BringToFront();
                    MessageBox.Show(this, e.Error.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    cambio(true);
                }
            }
            else if (!e.Cancelled && !this.IsDisposed)
            {
                ugClassHIV.DataSource = ds;
                cambio(true);
            }
        }

        private void ubSearchHIV_Click(object sender, EventArgs e)
        {
            cambio(false);
            bgwClassHIV.RunWorkerAsync();
        }

        private void ubExportHIV_Click(object sender, EventArgs e)
        {
            if (ugClassHIV.Rows.Count < 1)
            {
                MessageBox.Show(this, "There is no data to export", "Store Classification Report", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            System.Windows.Forms.SaveFileDialog dialogo = new System.Windows.Forms.SaveFileDialog();
            dialogo.DefaultExt = "xls";
            Infragistics.Win.UltraWinGrid.ExcelExport.UltraGridExcelExporter Exporter = new Infragistics.Win.UltraWinGrid.ExcelExport.UltraGridExcelExporter();
            if (dialogo.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                Exporter.Export(ugClassHIV, dialogo.FileName);
                if (MessageBox.Show(this, "Do you want to open the file?", "Store Classification Report", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    System.Diagnostics.Process.Start(dialogo.FileName);
                }
            }
        }

        private void uceCountryHIV_ValueChanged(object sender, EventArgs e)
        {
            try
            {
                ugClassHIV.DataSource = null;
            }
            catch { }
        }

        private void loader2_Load(object sender, EventArgs e)
        {

        }

        private void frmImportClassification_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (bgwClass.IsBusy) bgwClass.CancelAsync();
            if (bgwClassIV.IsBusy) bgwClassIV.CancelAsync();
            if (bgwClassHIV.IsBusy) bgwClassHIV.CancelAsync();
        }

    }
}
